// miniprogram/pages/publishing/publishing.js
const { $Message } = require('../../dist/base/index');
const app=getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value1:'',//悬赏名称
    value2:'',//手机号
    value3:'',//微信号
    value4:'',//详细信息
    value5:'',//物品交易的价格
    value6:'',//悬赏任务的价格//
    value7:'',//学习组队最大队伍人数//
    value8:'',//科研合作最大队伍人数//
    value9:'',//出行打车最大乘车人数
    value10:'',//出行目的地
    valueMine:{},//自己的技能标签
    valueSkill:'',//技能需求描述
    valueGoal:"",//学习的期望目标
    index:0,
    index1:0,
    index2:0,
    fileList: [],
    imgNumber:0,//现输入的图片个数
    array:["待选择","物品交易","悬赏任务","学习组队","科研合作","组队出行"],
    array1:["待选择","可议价","不可议价"],
    array2:["待选择","可议价","不可议价"],
    showSkill:false,
    show:false,
    date: '',//截止时间
    currentDate: "",//截止时间的时间戳
    skillNeed:[],//科研合作中对队友的技能需求集合
  },
    //打开时间选择器
  onDisplay() {
    this.setData({ show: true });
  },
    //关闭时间选择器
  onClose() {
    this.setData({ show: false });
  },
  //把时间戳改为可读标准时间
  formatDate(date) {
    date = new Date(date);
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
  },
  //确定截止时间
  onConfirm(event) {
    this.setData({
      show: false,
      date: this.formatDate(event.detail),
      currentDate:Date.parse(new Date(event.detail))
    });
  },
  //删除图片
  onDelete(e){
    const newFileList=this.data.fileList
    newFileList.splice(e.detail.index,1)
    this.setData({
      fileList:newFileList,
      imgNumber:newFileList.length
    })
  },
  //技能需求输入
  onChangeSkill(event){
    this.skill={
      value:event.detail,
      flag:0,
      checked:false
      }//每一条对队友的技能需求
  },
  //点击技能标签属性，选择是否删除
  onClickTag(e){
    const index=e.currentTarget.dataset.index
    const skillNeed=this.data.skillNeed
    wx.showModal({
      cancelColor: 'gray',
      confirmColor:"red",
      title: '提示',
      content: '确定要删除'+skillNeed[index].value+'吗？',
      success:res=>{
        if (res.confirm) {
          skillNeed.splice(index,1)
          this.setData({
            skillNeed:skillNeed
          })
          $Message({
            content: '成功删除',
            type: 'success'
        });
        } else if (res.cancel) {

        }
      },
      fail:err=>{
        $Message({
          content: '删除失败，请重新尝试',
          type: 'error'
      });
      }
    })
  },
   //异步上传图片，使云传输同步执行
 async up(event){   
    const newFileList=this.data.fileList
    var db=app.globalData.db;
    wx.showLoading({
      title: '上传中',
      mask:true
    })
    for(var i=0;i<event.detail.file.length;i++){
       await this.upload(i,event,newFileList)
      }
      setTimeout(function(){ wx.hideLoading({
        success: (res) => {
          wx.showToast({
            title: '上传成功',
            icon:"success",
            duration:800,
            mask:true
          })
        },
      })},500) 
 },
 //上传图片函数，这样写可以使await生效
 upload(i,event,newFileList){
  return wx.cloud.uploadFile({
    cloudPath: new Date().getTime() + '.png',
    filePath: event.detail.file[i].url, // 文件路径是数组，顺序取出
    success: res => {
      // get resource ID
      newFileList.push({url:res.fileID})
     this.setData({
      fileList:newFileList,
      imgNumber:newFileList.length
     })
    },
  })
 },
  /**
   * 生命周期函数--监听页面加载
   */
  //打开对队友技能需求的输入
  showPopupSkill(){
    if(this.data.value8==""){
      $Message({
        content: '请输入项目最大人数',
        type: 'warning'
    });
    return
    }
    if(this.data.skillNeed.length>=parseInt(this.data.value8)-1){
      $Message({
        content: '标签个数不能大于队友最大人数',
        type: 'warning'
    });
    return
    }
    this.setData({ showSkill: true });
  },
  //关闭对队友技能需求的输入
  onCloseSkill(){
    this.setData({ showSkill: false });
  },
  //输入名字
  inputName:function(e){
    this.setData({
      value1:e.detail.detail.value
    })
  },
  //输入联系电话
  inputContact:function(e){
    this.setData({
      value2:e.detail.detail.value
    })
  },
  //输入微信号
  inputWX:function(e){
    this.setData({
      value3:e.detail.detail.value
    })
  },
  //输入详细信息
  inputInfo:function(e){
    this.setData({
      value4:e.detail.detail.value
    })
  },
  //输入物品的价格
  inputPrice:function(e){
    this.setData({
      value5:e.detail.detail.value==""?"":'￥'+e.detail.detail.value
    })
  },
  //输入悬赏任务的价格
  inputDutyPrice:function(e){
    this.setData({
      value6:e.detail.detail.value==""?"":'￥'+e.detail.detail.value
    })
  },
 //输入学习组队最大队伍人数
  inputTeamSize(e){
    if(e.detail.detail.value<=1&&e.detail.detail.value!==""){
      $Message({
        content: '请输入正确的人数',
        type: 'warning'
    });
    this.setData({
      value7:""
    })
    return
    }
    this.setData({
      value7:e.detail.detail.value
    })
  },
  //输入学习的期望目标
  inputGoal(e){
    this.setData({
      valueGoal:e.detail.detail.value
    })
  },
  //切换悬赏类别
  bindChange:function(e){
    this.setData({
      index:e.detail.value
    })
  },

  //物品交易中选择是否可议价
  bindChange1:function(e){
    this.setData({
      index1:e.detail.value
    })
  },
  //悬赏任务中选择是否可议价
  bindChange2:function(e){
    this.setData({
      index2:e.detail.value
    })
  },
  //输入科研合作的最大人数
  inputSubjectSize(e){
    if(e.detail.detail.value<=1&&e.detail.detail.value!==""){
      $Message({
        content: '请输入正确的人数',
        type: 'warning'
    });
    this.setData({
      value8:""
    })
    return
    }
    this.setData({
      value8:e.detail.detail.value
    })
  },
  //输入自己的技能描述
  inputSubjectMine(e){
    this.setData({
      valueMine:{value:e.detail.detail.value,flag:1,checked:false}
    })
  },
  //输入出行最大人数
  inputTravelSize(e){
    if(e.detail.detail.value<=1&&e.detail.detail.value!==""){
      $Message({
        content: '请输入正确的人数',
        type: 'warning'
    });
    this.setData({
      value9:""
    })
    return
    }
    this.setData({
      value9:e.detail.detail.value
    })
  },
  //输入出行目的地
  inputTravelDestination(e){
    this.setData({
      value10:e.detail.detail.value
    })
  },
  //将单个技能信息堆入技能显示的数组
  onSkillNeed(){
    this.skillNeed=this.data.skillNeed
    this.skillNeed.push(this.skill)
    this.setData({
      skillNeed:this.skillNeed,
      showSkill:false,
      valueSkill:""
    })
  },
  //提交物品发布信息
  submitTransaction:function(){
    //若信息不全，则禁止发布
    if(this.data.value1==""||this.data.value2==""||this.data.value3==""||this.data.value4==""||this.data.value5==""||this.data.index==0||this.data.index1==0){
      $Message({
        content: '请确认补全所有信息',
        type: 'warning'
    });
   }
   else{
     if(this.data.fileList.length<1){
      $Message({
        content: '至少上传一张图片',
        type: 'warning'
    });
    return
     }
     var timestamp =
     Date.parse(new Date());
    //返回当前时间毫秒数
    timestamp = timestamp / 1000;
    //获取当前时间  
    var n = timestamp *
      1000; 
    var date = new Date(n); 
   //年
    var Y =
      date.getFullYear();
    //月
    
    var M = (date.getMonth()
      + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //日
    var D = date.getDate()
      < 10 ? '0' + date.getDate() :
      date.getDate();
    //时
    var h =
      date.getHours()<10?'0'+date.getHours():date.getHours();
   
    //分
    var m =
      date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes();
   
    //秒
    var s =
      date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds();
   //将数据装入数据库
     var db=app.globalData.db;
     db.collection('publishedTransaction').add({
       data:{
       datetime:Date.parse(new Date())/1000,
       name:this.data.value1,
       avatar:app.globalData.userInfo.avatarUrl,
       nickname:app.globalData.userInfo.nickName,
       price:parseFloat(this.data.value5.substr(1)),
       contact:[{avatar:app.globalData.userInfo.avatarUrl,nickname:app.globalData.userInfo.nickName,phone:this.data.value2,wx:this.data.value3,position:'卖家'}],
       info:this.data.value4,
       Class:this.data.index,
       isPrice:this.data.index1,
       fileList:this.data.fileList,
       othersOpenid:{},
       logs:Y+"年"+M+"月"+D+"日"+" "+h+":"+m+":"+s,
       isAccept:0,
       },
       success:res=>{
        $Message({
          content: '发布成功',
          type: 'success'
      });
        setTimeout(function(){
          wx.navigateBack({
            delta: 0,
          })
      },800)
       },
       fail:err=>{
        $Message({
          content: '发布失败，请尝试重新发布',
          type: 'error'
      });
       }
     })
   
   }
   },
   //提交任务发布信息
   submitDuty:function(){
    //若信息不全，则禁止发布
    if(this.data.value1==""||this.data.value2==""||this.data.value3==""||this.data.value4==""||this.data.value6==""||this.data.index2==0||this.data.date==""){
      $Message({
        content: '请确认补全所有信息',
        type: 'warning'
    });
   }
   else{
     var timestamp =
     Date.parse(new Date());
    //返回当前时间毫秒数
    timestamp = timestamp / 1000;
    //获取当前时间  
    var n = timestamp *
      1000; 
    var date = new Date(n); 
   //年
    var Y =
      date.getFullYear();
    //月
    
    var M = (date.getMonth()
      + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //日
    var D = date.getDate()
      < 10 ? '0' + date.getDate() :
      date.getDate();
    //时
    var h =
      date.getHours()<10?'0'+date.getHours():date.getHours();
   
    //分
    var m =
      date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes();
   
    //秒
    var s =
      date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds();
   //将数据装入数据库
     var db=app.globalData.db;
     db.collection('publishedDuty').add({
       data:{
       datetime:Date.parse(new Date())/1000,
       name:this.data.value1,
       avatar:app.globalData.userInfo.avatarUrl,
       nickname:app.globalData.userInfo.nickName,
       price:parseFloat(this.data.value6.substr(1)),
       contact:[{avatar:app.globalData.userInfo.avatarUrl,nickname:app.globalData.userInfo.nickName,phone:this.data.value2,wx:this.data.value3,position:'发布者'}],
       info:this.data.value4,
       Class:this.data.index,
       isPrice:this.data.index2,
       selectedDate:this.data.date,
       othersOpenid:{},
       currentDateStamp:this.data.currentDate,
       isAccept:0,
       logs:Y+"年"+M+"月"+D+"日"+" "+h+":"+m+":"+s
       },
       success:res=>{
        $Message({
          content: '发布成功',
          type: 'success'
      });
        setTimeout(function(){
          wx.navigateBack({
            delta: 0,
          })
      },800)
       },
       fail:err=>{
        $Message({
          content: '发布失败，请尝试重新发布',
          type: 'error'
      });
       }
     })
   
   }
   },
   //提交学习组队的信息
   submitStudyTeam(){
      //若信息不全，则禁止发布
    if(this.data.value1==""||this.data.value2==""||this.data.value3==""||this.data.value4==""||this.data.value7==""||this.data.valueGoal==""){
      $Message({
        content: '请确认补全所有信息',
        type: 'warning'
    });
   }
   else{
     var timestamp =
     Date.parse(new Date());
    //返回当前时间毫秒数
    timestamp = timestamp / 1000;
    //获取当前时间  
    var n = timestamp *
      1000; 
    var date = new Date(n); 
   //年
    var Y =
      date.getFullYear();
    //月
    
    var M = (date.getMonth()
      + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //日
    var D = date.getDate()
      < 10 ? '0' + date.getDate() :
      date.getDate();
    //时
    var h =
      date.getHours()<10?'0'+date.getHours():date.getHours();
   
    //分
    var m =
      date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes();
   
    //秒
    var s =
      date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds();
   //将数据装入数据库
     var db=app.globalData.db;
     db.collection('publishedStudy').add({
       data:{
       datetime:Date.parse(new Date())/1000,
       name:this.data.value1,
       avatar:app.globalData.userInfo.avatarUrl,
       nickname:app.globalData.userInfo.nickName,
       price:parseFloat(this.data.value6),
       contact:[{avatar:app.globalData.userInfo.avatarUrl,nickname:app.globalData.userInfo.nickName,phone:this.data.value2,wx:this.data.value3,position:'组织者'}],
       info:this.data.value4,
       teamSize:this.data.value7,
       goal:this.data.valueGoal,
       othersOpenid:{},
       isAccept:0,
       teamMember:[app.globalData.userInfo.avatarUrl],
       count:1,
       logs:Y+"年"+M+"月"+D+"日"+" "+h+":"+m+":"+s
       },
       success:res=>{
        $Message({
          content: '发布成功',
          type: 'success'
      });
        setTimeout(function(){
          wx.navigateBack({
            delta: 0,
          })
      },800)
       },
       fail:err=>{
        $Message({
          content: '发布失败，请尝试重新发布',
          type: 'error'
      });
       }
     })
   
   }
   },
//提交组队出行的信息
   submitTravel(){
        //若信息不全，则禁止发布
    if(this.data.value1==""||this.data.value2==""||this.data.value3==""||this.data.value4==""||this.data.value9==""||this.data.value10==""){
      $Message({
        content: '请确认补全所有信息',
        type: 'warning'
    });
   }
   else{
     var timestamp =
     Date.parse(new Date());
    //返回当前时间毫秒数
    timestamp = timestamp / 1000;
    //获取当前时间  
    var n = timestamp *
      1000; 
    var date = new Date(n); 
   //年
    var Y =
      date.getFullYear();
    //月
    
    var M = (date.getMonth()
      + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //日
    var D = date.getDate()
      < 10 ? '0' + date.getDate() :
      date.getDate();
    //时
    var h =
      date.getHours()<10?'0'+date.getHours():date.getHours();
   
    //分
    var m =
      date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes();
   
    //秒
    var s =
      date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds();
   //将数据装入数据库
     var db=app.globalData.db;
     db.collection('publishedTravel').add({
       data:{
       datetime:Date.parse(new Date())/1000,
       name:this.data.value1,
       avatar:app.globalData.userInfo.avatarUrl,
       nickname:app.globalData.userInfo.nickName,
       price:parseFloat(this.data.value6),
       contact:[{avatar:app.globalData.userInfo.avatarUrl,nickname:app.globalData.userInfo.nickName,phone:this.data.value2,wx:this.data.value3,position:'组织者'}],
       info:this.data.value4,
       Class:this.data.index,
       travelSize:this.data.value9,
       travelDestination:this.data.value10,
       othersOpenid:{},
       isAccept:0,
       teamMember:[app.globalData.userInfo.avatarUrl],
       count:1,
       logs:Y+"年"+M+"月"+D+"日"+" "+h+":"+m+":"+s
       },
       success:res=>{
        $Message({
          content: '发布成功',
          type: 'success'
      });
        setTimeout(function(){
          wx.navigateBack({
            delta: 0,
          })
      },800)
       },
       fail:err=>{
        $Message({
          content: '发布失败，请尝试重新发布',
          type: 'error'
      });
       }
     })
   
   }
   },
//提交项目合作的信息
submitSubjectTeam(){
    //若信息不全，则禁止发布
if(this.data.value1==""||this.data.value2==""||this.data.value3==""||this.data.value4==""||this.data.value8==""){
  $Message({
    content: '请确认补全所有信息',
    type: 'warning'
});
}
else{

 var timestamp =
 Date.parse(new Date());
//返回当前时间毫秒数
timestamp = timestamp / 1000;
//获取当前时间  
var n = timestamp *
  1000; 
var date = new Date(n); 
//年
var Y =
  date.getFullYear();
//月

var M = (date.getMonth()
  + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
//日
var D = date.getDate()
  < 10 ? '0' + date.getDate() :
  date.getDate();
//时
var h =
  date.getHours()<10?'0'+date.getHours():date.getHours();

//分
var m =
  date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes();

//秒
var s =
  date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds();
//将数据装入数据库
 var db=app.globalData.db;
 db.collection('publishedSubject').add({
   data:{
   datetime:Date.parse(new Date())/1000,
   name:this.data.value1,
   avatar:app.globalData.userInfo.avatarUrl,
   nickname:app.globalData.userInfo.nickName,
   contact:[{avatar:app.globalData.userInfo.avatarUrl,nickname:app.globalData.userInfo.nickName,phone:this.data.value2,wx:this.data.value3,position:'组织者',tags:[this.data.valueMine.value]}],
   info:this.data.value4,
   subjectSize:this.data.value8,
   othersOpenid:{},
   isAccept:0,
   teamMember:[app.globalData.userInfo.avatarUrl],
   count:1,
   tags:[this.data.valueMine,...this.data.skillNeed],
   logs:Y+"年"+M+"月"+D+"日"+" "+h+":"+m+":"+s
   },
   success:res=>{
    $Message({
      content: '发布成功',
      type: 'success'
  });
    setTimeout(function(){
      wx.navigateBack({
        delta: 0,
      })
  },800)
   },
   fail:err=>{
    $Message({
      content: '发布失败，请尝试重新发布',
      type: 'error'
  });
   }
 })

}
},
  onLoad: function (options) {

    this.skillNeed=[]



    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //加载电话号码和微信号，方便直接使用
    var db=app.globalData.db;
    db.collection('user').where({
      _openid:app.globalData.openid
    }).get({
      success:res=>{
        if(res.data.length===0){
          wx.showModal({
            title:"完善个人信息后才能发布消息，是否前往完善个人信息？",
            confirmColor: 'red',
            confirmText:'前往',
            cancelText:'返回',
            success:res=>{
              if (res.confirm) {
                wx.navigateTo({
                  url: '../info/info',
                })
              } else if (res.cancel) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        }
        this.setData({
          value2:res.data[0].phone,
          value3:res.data[0].wx
        })
      },
      fail:err=>{
        wx.navigateTo({
          url: '../publishing/publishing',
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})